from typing import Dict, Any, List
import os
from .base_formatter import BaseFormatter
from ..builders.html_builder import HTMLBuilder

class HTMLFormatter(BaseFormatter):
    """HTML报告格式化器"""
    
    def __init__(self, output_dir: str):
        super().__init__(output_dir)
        self.builder = HTMLBuilder()
    
    def format_report(self, results: List[Dict[str, Any]], scan_info: Dict[str, Any]) -> None:
        """生成HTML格式的报告
        
        Args:
            results: 扫描结果列表
            scan_info: 扫描信息字典
        """
        filename = os.path.join(self.output_dir, 'scan_report.html')
        
        # 准备扫描信息
        formatted_scan_info = {
            'start_time': self._format_timestamp(scan_info['start_time']),
            'end_time': self._format_timestamp(scan_info['end_time']),
            'total_hosts': scan_info['total_hosts'],
            'total_ports': scan_info['total_ports']
        }
        open_ports = len([r for r in results if r['status'] == 'open'])
        
        # 构建HTML内容
        content = []
        
        # 添加头部
        content.append(self.builder.build_header())
        
        # 添加摘要
        content.append(self.builder.build_summary(formatted_scan_info, open_ports))
        
        # 添加控制按钮
        content.append(self.builder.build_controls())
        
        # 添加表格头部
        content.append(self.builder.build_table_header())
        
        # 添加表格内容
        status_map = {
            'open': ('开放', 'open'),
            'closed': ('关闭', 'closed'),
            'filtered': ('被过滤', 'filtered')
        }
        
        for index, result in enumerate(sorted(results, key=lambda x: (x['target'], x['port'])), 1):
            status_text, status_class = status_map.get(result['status'], (result['status'], ''))
            service = result['service'] if result['service'] else "未知"
            latency = f"{result['latency']}ms" if result['latency'] else "N/A"
            
            # 获取服务详细信息
            details = []
            if result['service_info'] and result['status'] == 'open':
                details = self._get_service_details(result['service_info'])
                
                # 为HTTP(S)服务添加访问链接
                if result['service_info'].get('name') in ['http', 'https']:
                    protocol = 'https' if result['service_info'].get('ssl') or result['service_info']['name'] == 'https' else 'http'
                    url = f"{protocol}://{result['target']}:{result['port']}"
                    details.append(f'<a href="{url}" target="_blank" class="http-link">访问网站</a>')
            
            details_html = '<br>'.join(details) if details else '无详细信息'
            
            # 添加表格行
            content.append(self.builder.build_table_row(
                index=index,
                result=result,
                status_text=status_text,
                status_class=status_class,
                service=service,
                latency=latency,
                details_html=details_html
            ))
        
        # 添加尾部
        content.append(self.builder.build_footer())
        
        # 写入文件
        self._write_file(filename, '\n'.join(content)) 